package controllers;

import models.*;
import play.data.validation.*;
import javax.persistence.PersistenceException;

public class Security extends Secure.Security {
	public static boolean isEmployee;

    static boolean authenticate(@Required (message="Username is required")String username, @Required (message="Password is required")String password) {
		if(username.equals("") || password.equals("")){
			validation.keep(); 	//keeps error messages for next request
			params.put("login_error", "Username and password are required"); //for frontend to know which dialog had errors
			params.flash();		//keeps param values from form to repopulate
			return false;
		}
		
		isEmployee = false;
        Customer customer = Customer.find("byUsername", username).first();
		if(customer == null){
			//Username not found in customer table, try employee table
			Employee employee = Employee.find("byUsername", username).first();
			if(employee == null){
				//No such customer or employee username
			}else{
				//This user is an employee
				isEmployee = true;
				//Validate employee's password entered
				if(employee.password.equals(password)){
					//Authentication successful (employee)
					return true;
				}else{
					//Password wrong
				}
			}
		}else{
			//This user is a customer
			//Validate customer's password entered
			if(customer.password.equals(password)){
				//Authentication successful (customer)
				return true;
			}else{
				//Password wrong
			}
		}
		
		//Either wrong username/pwd
		flash.put("login_error", "Incorrect username and/or password");
        return false;
    }

    //send user to index (home page) when they logout
    static void onDisconnected() {        
    	try {
			Index.index();
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }

    //send user to portfolio area when they login successfully
    static void onAuthenticated(){
        try {
			if(isEmployee){
				EmployeeArea.index();
			}else{
				CustomerArea.portfolio();
			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
    }
	
	static boolean check(String profile){
		if("employee".equals(profile)){
			return isEmployee;
		}
		if("customer".equals(profile) && !isEmployee){
			return true;
		}
		return false;
	}
}
